package com.nanbei.future;

import java.util.concurrent.*;

/**
 * @ClassDescription:
 * @JdkVersion: 1.8
 * @Author: libs
 * @Created: 2024/9/25 15:06
 */
public class FutureTaskDemo1 {
    public static void main(String[] args) throws Exception {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        FutureTask<String> stringFutureTask = new FutureTask<>(() -> {
            TimeUnit.MILLISECONDS.sleep(2000);
            return "有返回值的 callable 接口";
        });

        // 通过thread 类来执行FutureTask
        /*Thread thread = new Thread(stringFutureTask);
        thread.start();
        System.out.println(stringFutureTask.get());*/



        // 通过线程池的方式执行 FutureTask
        /*threadPool.submit(stringFutureTask);

        long startTime = System.currentTimeMillis();
        System.out.println("主程序在等待获取线程执行的结果的开始时间为:" + startTime);
        // FutureTask 在获取执行结果时会阻塞主线程
        System.out.println(stringFutureTask.get());
        threadPool.shutdown();

        System.out.println("主程序执行结束的总时间为：" + (System.currentTimeMillis() - startTime));*/

        // 通过轮询的方式获取线程执行结果
        threadPool.submit(stringFutureTask);
        while (true){
            if (stringFutureTask.isDone()){
                System.out.println(stringFutureTask.get());
                break;
            }else {
                System.out.println("通过轮询方式获取结果");
                TimeUnit.MILLISECONDS.sleep(400);
            }
        }

        threadPool.shutdown();


    }
}
